package com.modules.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

/**
 * Created by lewis on 2017/6/16.
 */
public class OptionTag extends SimpleTagSupport implements OptionSupport{

    private String name;
    private String value;
    private String type = OptionTypeConstant.TYPE_AUTO;
    /*所有处理对象*/
    OptionSupportHandler handler = new OptionSupportHandler();
    /**
     * 增加选项，同名选项将被覆盖
     */
    public void addOption(Option opt) {
        handler.addOption(opt);
    }

    /**
     * 获得所有选项
     */
    public List<Option> getOptions() {
        return handler.getOptions();
    }
    /**
     * 判断是否包含某个选项
     */
    public boolean contains(String key) {
        return handler.contains(key);
    }


    public void doTag() throws JspException,IOException
    {
        //获取标签体内容
        JspFragment jspFragment = getJspBody();
        if(jspFragment !=null){
            StringWriter writer = new StringWriter();
            jspFragment.invoke(writer);
            String body =writer.getBuffer().toString();
            setValue(body);
        }


        Option option = getOption();
        if(option != null)
        {
            OptionSupport parent = (OptionSupport) getParent();
            try{
                parent.addOption(option);
            } catch(Exception ex)
            {
            }
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    private Option getOption()
    {
		/*
		 *  此处的处理逻辑为 options 定义优先于 value 的定义
		 */
        if(handler.size() > 0)
        {
            return OptionUtils.createOption(name, handler.getJSExpression(), OptionTypeConstant.TYPE_OBJECT);
        }
        else if(value != null)
        {
            return OptionUtils.createOption(name, value, type) ;
        }
        return null;
    }
    /**
     * 根据选项类型返回选项的表达式
     */
    public String getJSExpression() {
        return null;
    }
}
